# -*- coding: UTF-8 -*-
import md5
import os

from pyramid.view import view_config
from pyramid.renderers import render_to_response
from pyramid.httpexceptions import HTTPFound
from sqlalchemy import and_, or_, desc
import transaction

from pyramid.security import (
        remember,
        forget,
        IAuthenticationPolicy,
        )

from ..models.meta import (
    DBSession,
    )

from ..models.models import (
    Coupon,
    User,
    Role
    )

from ..freedom.dateutil.parser import parse
from ..freedom.paginator import Paginator


@view_config(route_name='user_login')
def user_login(request):
    if request.method=="GET":
        if request.params.get('backurl'):
            request.session.flash(u"您需要先登陆，才能继续!")

        return render_to_response('/front/user/login.html', {}, request = request)
    if request.method=="POST":
        #capcha check
        #for test comment first
        #if request.session['CONSTANT_Captcha'] != request.params.get('captcha'):
            #request.session.flash(u"验证码错误!")
            #return render_to_response('/front/business/login.html', {}, request = request)

        email = request.params.get('email', '')
        password = request.params.get('password', '')
        if(email and password):
            user_q = DBSession().query(User).filter(User.enable==1).filter(User.roleid==2)
            users = user_q.filter(and_(User.email==email, User.password == md5.new(password).hexdigest())).all()
            if(users and len(users) == 1):
                request.session['user_email'] = email
                request.session['user_id'] = users[0].id
                headers = remember(request, 'role:user')
                return HTTPFound(location = request.params.get('backurl') or request.route_url('user_page', page='index'), headers = headers)
            else:
                request.session.flash(u"邮件或者密码不正确!")
                return render_to_response('front/user/login.html', {}, request = request)

@view_config(route_name='user_register')
def user_register(request):
    #submit from add
    if 'form.submitted' in request.params:
        user = User()

        user.email = request.params.get('email')
        user.password = md5.new(request.params.get('password')).hexdigest()
        user.role = DBSession.query(Role).filter(Role.name == 'normal').first()
        user.enable = True

        DBSession.add(user)
       
        return render_to_response('/front/user/registersuccess.html', {'user':user}, request = request)

    #render
    return render_to_response('/front/user/register.html', {}, request = request)

@view_config(route_name='user_page', permission='user_view')
def user_page(request):
    exec('result = user_%s(request)' % request.matchdict.get('page') or 'index')
    return result

def user_index(request):
    #get user info
    userid = int(request.session['user_id'])
    user_q = DBSession().query(User)
    user = user_q.get(userid)
    return render_to_response('/front/user/index.html', {'user':user}, request = request)

def user_registersuccess(request):
    return render_to_response('/front/user/registersuccess.html', {}, request = request)

def user_mycoupons(request):
    #get user info
    userid = int(request.session['user_id'])
    user_q = DBSession().query(User)
    user = user_q.get(userid)
    #get user's coupon info
    #tmpl_context = {'users':paginator, 'search_fields': search_fields}
    coupon_paginator = Paginator(user.couponrandoms, 5)
    coupon_paginator.page_from_url(request.url)
    return render_to_response('/front/user/mycoupons.html', {'user':user, 'couponrandoms':coupon_paginator}, request = request)
